/*
 * Demoiselle Framework
 * Copyright (C) 2011 SERPRO
 * ----------------------------------------------------------------------------
 * This file is part of Demoiselle Framework.
 * 
 * Demoiselle Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not,  see <http://www.gnu.org/licenses/>
 * or write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA  02110-1301, USA.
 * ----------------------------------------------------------------------------
 * Este arquivo é parte do Framework Demoiselle.
 * 
 * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou
 * modificá-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação
 * do Software Livre (FSF); na versão 2 da Licença.
 * 
 * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
 * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
 * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/GPL em português
 * para maiores detalhes.
 * 
 * Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título
 * "LICENCA.txt", junto com esse programa. Se não, acesse o Portal do Software Público
 * Brasileiro no endereço www.softwarepublico.gov.br ou escreva para a Fundação do Software
 * Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
 
 * @author Tarcizio Vieira Neto (tarcizio.vieira@owasp.org) <a href="http://www.serpro.gov.br">SERPRO</a>
 * @created 2011
 */
package br.gov.frameworkdemoiselle.security.filter.authentication;

import java.io.IOException;
import java.util.Date;
import java.util.Stack;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.owasp.appsensor.errors.AppSensorException;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.errors.AuthenticationCredentialsException;
import org.owasp.esapi.errors.AuthenticationException;

import br.gov.frameworkdemoiselle.data.EsapiConfig;
import br.gov.frameworkdemoiselle.security.UserManager;

/**
 * Servlet Filter implementation class LoginFilter
 */
public class AuthenticationFilter implements Filter {
		
	/**
	 * Default constructor.
	 */
	public AuthenticationFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		HttpSession session = request.getSession(true);
				
		//checkIfAuthenticated()		
		// figure out who the current user is
		try {
			ESAPI.authenticator().login(request, response);
		} catch( AuthenticationException e ) {
			if (e instanceof AuthenticationCredentialsException )
				new AppSensorException("AE2", "Multiple Failed Passwords", "Multiple bad passwords are entered for user: "+ESAPI.authenticator().getCurrentUser().getAccountName());
			
			ESAPI.authenticator().logout();
			request.setAttribute("message", "Authentication failed");
			RequestDispatcher dispatcher = request.getRequestDispatcher(EsapiConfig.getInstance().getLoginPath()); //!!!!
			dispatcher.forward(request, response);
			return;
		}
				
		//checkForAE1(session, request.getParameter(ESAPI.securityConfiguration().getUsernameParameterName()));
		//checkForAE3(session);
		
						
		//*????
		// resp.sendRedirect("https://localhost:8443/AppSensorDemo/login.jsp");
		if (UserManager.isSessionValid(request)) {
			// logged in, continue filters
			// chain.doFilter(request, response);
			chain.doFilter(req, res);
		} else {
			// not logged in, redirect to login page, unless is login request
			// last exception is for REST communication point
			String URI = request.getRequestURI();
			if (URI.contains("login.jsp") || URI.contains("Login") || URI.contains("AppSensorResponseAgent") || URI.contains(".jpg")) {
				chain.doFilter(req, res);
			} else {
				// String redirectURL="https://"+request.getServerName()+":"+request.getServerPort()+"/AppSensorDemo/"+"login.jsp";
				String contextPath = request.getContextPath(); // gives "/AppSensorDemo" as result or wherever this is deployed
				String redirectURL = contextPath + "/login.jsp";
				// resp.sendRedirect("https://localhost:8443/AppSensorDemo/login.jsp");
				response.sendRedirect(redirectURL);
			}
		}

	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}
	
	public void checkForAE1(HttpSession session, String username) {
		Stack<String> usernamesTried = ESAPI.httpUtilities().getSessionAttribute("loginsAttempt");
        if (usernamesTried == null)
        {
            usernamesTried = new Stack<String>();
            session.setAttribute("loginsAttempt", usernamesTried);
        }
        
        if (!usernamesTried.contains(username)) {
        	if (usernamesTried.size() <= loginAttemptLimit) {
        		usernamesTried.add(username);
        	} else new AppSensorException("AE1", "Use of Multiple Usernames", "Multiple usernames are attempted when logging into the application."); 
        }
	}
	
	private int loginAttemptLimit = 5;
	
	public void checkForAE3(HttpSession session) {
		 synchronized( session.getId().intern() ) {
		        Stack<Date> times = ESAPI.httpUtilities().getSessionAttribute("timesLoginAttempt");
		        if (times == null)
		        {
		            times = new Stack<Date>();
		            times.push(new Date(0));
		            session.setAttribute("timesLoginAttempt", times);
		        }
		        times.push(new Date());
		        if (times.size() >= hits)
		        {
		            times.removeElementAt(0);
		        }
		        Date newest = times.get(times.size() - 1);
		        Date oldest = times.get(0);
		        long elapsed = newest.getTime() - oldest.getTime();        
		        if (elapsed < period * 1000) // seconds
		        {
		        	new AppSensorException("AE3", "High Rate of Login Attempts", "The rate of login attempts becomes too high (possibly indicating an automated login attack).");
		            return;
		        }
	        }
	}
    private int hits = 5;
    private int period = 10;
    //private static final String HITS = "hits";
    //private static final String PERIOD = "period";
}
